package com.wosai.teach.handler;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.android.agnetty.core.event.ExceptionEvent;
import com.android.agnetty.core.event.MessageEvent;
import com.android.agnetty.future.http.HttpHandler;
import com.android.agnetty.utils.LogUtil;
import com.wosai.teach.dao.UserDao;
import com.wosai.teach.pojo.JsonResult;
import com.wosai.teach.pojo.User;
import com.wosai.teach.utils.AppGlobal;

public class LoginHandler extends HttpHandler {

	public LoginHandler(Context context) {
		super(context);
	}

	@Override
	public boolean onEncode(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public boolean onCompress(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public boolean onDecompress(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public boolean onDecode(MessageEvent evt) throws Exception {
		return false;
	}

	@Override
	public void onHandle(MessageEvent evt) throws Exception {
		String response = new String((byte[]) evt.getData(), "utf-8");
		LogUtil.d(LoginHandler.class.getCanonicalName() + response);
		if (!TextUtils.isEmpty(response)) {
			System.out.println(response);
			JsonResult jr = JSON.parseObject(response, JsonResult.class);
			if (jr.getResult() == 0) {
				User user = JSON.parseObject(jr.getObject().toString(),
						User.class);
				AppGlobal.user = user;
				UserDao personalDao = new UserDao();
				personalDao.saveOrUpdateUser(user);
				evt.getFuture().commitComplete(true);
			} else {
				evt.getFuture().commitComplete(false);
			}
		}
	}

	@Override
	public void onException(ExceptionEvent evt) {
		evt.getException().printStackTrace();
	}

	@Override
	public void onDispose() {

	}

}
